package me.mononin.factory.preseneter.account;

import android.text.TextUtils;

import net.qiujuer.genius.kit.handler.Run;
import net.qiujuer.genius.kit.handler.runable.Action;

import java.util.regex.Pattern;

import me.mononin.common.common.Common;
import me.mononin.common.factory.data.DataSource;
import me.mononin.common.factory.presenter.BasePresenter;
import me.mononin.factory.R;
import me.mononin.factory.data.helper.AccountHelper;
import me.mononin.factory.model.api.account.RegisterModel;
import me.mononin.factory.model.db.User;
import me.mononin.factory.persistence.Account;

public class RegisterPresenter extends BasePresenter<RegisterContract.View>
        implements RegisterContract.Presenter,DataSource.Callback<User>{

    public RegisterPresenter(RegisterContract.View view) {
        super(view);
    }

    @Override
    public void register(String account, String password, String name) {

        //注册时开启一个Loading
        start();

        // 得到View接口
        RegisterContract.View view = getView();

        if (!checkMobile(account)){
            //显示当前密码不合法
            view.showError(R.string.data_account_register_invalid_parameter_mobile);
        }else if (name.length()<2){
            //显示名称大于2位
            view.showError(R.string.data_account_register_invalid_parameter_name);
        }else if (password.length()<6){
            //显示密码大于6位
            view.showError(R.string.data_account_register_invalid_parameter_password);
        }else {
            RegisterModel model = new RegisterModel(account,password,name, Account.getPushId());
            AccountHelper.register(model,this);
        }


    }

    /**
     * 检查手机号码是否合法
     * @param phone 手机账号
     * @return true
     */
    @Override
    public boolean checkMobile(String phone) {
        //判断手机号码不为空且合法
        return !TextUtils.isEmpty(phone)
                //具体正则在common包中定义
                && Pattern.matches(Common.Constance.REGEX_MOBILE,phone);

    }

    @Override
    public void onDataLoaded(User user) {
        //获取当前视图
        final RegisterContract.View view = getView();

        if (view==null){
            return;
        }

        Run.onUiAsync(new Action() {
            @Override
            public void call() {
                view.registerSuccess();
            }
        });
    }

    @Override
    public void onDataNotAvailable(final int res) {
        //获取当前视图
        final RegisterContract.View view = getView();

        if (view==null){
            return;
        }

        Run.onUiAsync(new Action() {
            @Override
            public void call() {
                view.showError(res);
            }
        });
    }
}
